package cn.qidd.keep.product.controller;

import cn.qidd.keep.domain.core.Result;
import cn.qidd.keep.domain.core.dict.ProductStatus;
import cn.qidd.keep.domain.document.Product;
import cn.qidd.keep.domain.document.QProduct;
import cn.qidd.keep.domain.web.BaseController;
import cn.qidd.keep.domain.web.UserVO;
import cn.qidd.keep.product.model.product.CreateProductRequest;
import cn.qidd.keep.product.model.product.ProductPublicParam;
import cn.qidd.keep.product.model.product.ProductSearchParams;
import cn.qidd.keep.product.model.product.UpdateProductRequest;
import cn.qidd.keep.product.repository.ProductRepository;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static cn.qidd.keep.domain.core.Constants.TOKEN;

@RestController
@RequestMapping("/api/product")
@Api(value = "ProductController", description = "产品相关操作")
public class ProductController extends BaseController {

    @Resource
    private ProductRepository productRepository;

    @GetMapping("/findAllPublicProductList")
    @ApiOperation(value = "查询所有未删除的产品", notes = "查询所有未删除的产品")
    public Result findAllPublicProductList() {
        logger.debug("Rest request to findAllPublicProductList");
        QProduct qProduct = QProduct.product;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qProduct.isDelete.eq(false));
        List<Product> list = Lists.newArrayList(productRepository.findAll(builder));
        return new Result<>(Result.Status.SUCCESS, list);
    }

    @PostMapping("/addProduct")
    @ApiOperation(value = "创建产品", notes = "创建产品")
    private Result addProduct(@ApiIgnore @RequestHeader(TOKEN) String token, @Validated @RequestBody CreateProductRequest request) {
//        logger.debug("Rest request to add product: {}", request);
        UserVO userVO = getUserByToken(token);
        Product product = new Product();
        BeanUtils.copyProperties(request, product);
        product.setProductStatus(ProductStatus.NO_PUBLIC);
        product.setCreateTime(new Date());
        product.setIsDelete(false);
        product.setOperatorName(userVO.getUserName());
        product.setOperatorRealName(userVO.getRealName());
        product.setOperatorTime(new Date());
        productRepository.save(product);
        return new Result(Result.Status.SUCCESS, "创建成功");
    }

    @PutMapping("/updateProduct")
    @ApiOperation(value = "编辑产品", notes = "编辑产品")
    private Result updateProduct(@ApiIgnore @RequestHeader(TOKEN) String token, @Validated @RequestBody UpdateProductRequest request) {
        logger.debug("Rest request to update product: {}", request);
        UserVO userVO = getUserByToken(token);
        Product product = productRepository.findById(request.getId()).orElseThrow(RuntimeException::new);
        product.setProductName(request.getProductName());
        product.setProductContent(request.getProductContent());
        product.setProductPrice(request.getProductPrice());
        product.setRemark(request.getRemark());
        product.setOperatorName(userVO.getUserName());
        product.setOperatorRealName(userVO.getRealName());
        product.setOperatorTime(new Date());
        productRepository.save(product);
        return new Result(Result.Status.SUCCESS, "编辑成功");
    }

    @DeleteMapping("/deleteProduct/{id}")
    @ApiOperation(value = "删除产品", notes = "删除产品")
    private Result deleteProduct(@ApiIgnore @RequestHeader(TOKEN) String token, @PathVariable String id) {
        logger.debug("Rest request delete product by id: {}", id);
        UserVO userVO = getUserByToken(token);
        Product product = productRepository.findById(id).orElseThrow(RuntimeException::new);
        product.setIsDelete(true);
        product.setOperatorName(userVO.getUserName());
        product.setOperatorRealName(userVO.getRealName());
        product.setOperatorTime(new Date());
        productRepository.save(product);
        return new Result(Result.Status.SUCCESS, "删除成功");
    }

    @GetMapping("/findListByPage")
    @ApiOperation(value = "分页查询所有产品", notes = "分页查询所有产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "integer", paramType = "query",
                    value = "页数 (1..N)"),
            @ApiImplicitParam(name = "pageSize", defaultValue = "10", dataType = "integer", paramType = "query",
                    value = "每页大小"),
            @ApiImplicitParam(name = "sort", dataType = "string", paramType = "query",
                    value = "依据什么排序: 属性名1 asc,属性名2 desc. ")
    })
    public Result findListByPage(@ApiIgnore Pageable pageable, ProductSearchParams params) {
        logger.debug("Rest request to findListByPage");
        BooleanBuilder condition = params.generateSearchCondition();
        Page<Product> page = productRepository.findAll(condition, pageable);
        return new Result<>(Result.Status.SUCCESS, page);
    }

    @PutMapping("/publicProduct")
    @ApiOperation(value = "发布产品", notes = "发布产品")
    public Result publicProduct(@ApiIgnore @RequestHeader(TOKEN) String token,
                                @RequestBody ProductPublicParam param) {
        logger.debug("Rest request to public product by id: {}", param.getId());
        UserVO userVO = getUserByToken(token);
        Product product = productRepository.findById(param.getId()).orElseThrow(RuntimeException::new);
        product.setProductStatus(ProductStatus.PUBLIC);
        product.setOperatorTime(new Date());
        product.setOperatorRealName(userVO.getRealName());
        product.setOperatorName(userVO.getUserName());
        productRepository.save(product);
        return new Result(Result.Status.SUCCESS, "发布成功");

    }


}
